﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using ShevaEngine.Core.Interfaces;
using ShevaEngine.Core.Modules.Scenes;

namespace ShevaEngine.Core.Modules.Audio
{
    /// <summary>
    /// Sound class.
    /// </summary>
    public class Sound : SceneObject, IUpdateAble
    {
        /// <summary>Emitter.</summary>
        private AudioEmitter Emitter;
        /// <summary>Sound effect.</summary>
        private SoundEffectInstance SoundEffect;
        /// <summary>Is lopped</summary>
        public Boolean IsLooped { get { return this.SoundEffect.IsLooped; } set { this.SoundEffect.IsLooped = value; } }
        /// <summary>Is 3D.</summary>
        public Boolean Is3D { get; private set; }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="soundEffect"></param>
        public Sound(string soundEffect, Boolean is3D = false)
            : base()
        {
            this.Emitter = new AudioEmitter();
            this.SoundEffect = AudioSystem.Instance.GetSoundEffect(soundEffect).CreateInstance();
            this.Is3D = is3D;            
        }

        /// <summary>
        /// Method starts playing sound.
        /// </summary>
        public void Play()
        {            
            this.SoundEffect.Play();
        }

        /// <summary>
        /// Method Update().
        /// </summary>
        /// <param name="time"></param>
        public void Update(GameTime time)
        {
            this.Emitter.Position = this.World.Translation;
            this.Emitter.Forward = Vector3.Forward;
            this.Emitter.Up = Vector3.Up;
            this.Emitter.Velocity = Vector3.Zero;            
        }

        /// <summary>
        /// Apply 3D method.
        /// </summary>
        /// <param name="listeners"></param>
        public void Apply3D(AudioListener[] listeners)
        {
            this.SoundEffect.Apply3D(listeners, this.Emitter);
        }


        public override void Transform(Matrix matrix)
        {
            base.Transform(matrix);

            this.Emitter.Position = this.World.Translation;
            this.Emitter.Forward = Vector3.Forward;
            this.Emitter.Up = Vector3.Up;
            this.Emitter.Velocity = Vector3.Zero;  
        }
    }
}
